#include "UdpSocket.h"
#include <memory>
#include <netinet/udp.h>
#include "IpV4Address.h"
#include "IpV6Address.h"
#include "Util.h"
namespace xncc {
namespace foundation {
    UdpSocket::~UdpSocket() = default;

    void UdpSocket::bind() { bind(sockfd_); }

    void UdpSocket::bind(int sockfd)
    {
        int ret = -1;
        if (sockaddr_->Type() == shared::XNCC_ADDR_TYPE::IPV4_UDP) {
            const auto v4Addr = std::dynamic_pointer_cast<IpV4Address>(sockaddr_);
            ret = ::bind(sockfd, v4Addr->getSockAddr(), static_cast<socklen_t>(sizeof(struct sockaddr_in)));
        }
        else if (sockaddr_->Type() == shared::XNCC_ADDR_TYPE::IPV6_UDP) {
            const auto v6Addr = std::dynamic_pointer_cast<IpV6Address>(sockaddr_);
            ret = ::bind(sockfd, v6Addr->getSockAddr(), static_cast<socklen_t>(sizeof(struct sockaddr_in6)));
        }
        if (ret < 0) {
            throw shared::system_exception("bind socket failed");
        }
    }
}  // namespace foundation
}  // namespace xncc